#!/usr/bin/env python3
# coding=utf-8
"""宁波跳板机和腾讯云跳板机操作不同, 分布把跳板机打印的服务列表贴在下面j1, j2两个变量里即可"""
import re
import os
import pexpect, struct, fcntl, termios, signal, sys, functools

user="tianzhipeng"
j1 = '''
[0  ] 10.10.10.155        nb-AudiX-dico1
[1  ] 10.10.10.156        nb-dmp-01
[2  ] 10.10.1.197         13.client.adh
[3  ] 10.10.1.196         12.client.adh
[4  ] 10.10.1.194         10.client.adh
[5  ] 10.10.1.212         18.client.adh
[6  ] 10.10.1.198         14.client.adh
[7  ] 10.10.1.211         17.client.adh
[8  ] 10.10.1.200         16.client.adh
[9  ] 10.10.1.199         15.client.adh
[10 ] 10.10.1.195         11.client.adh
[11 ] 10.10.1.193         9.client.adh
[12 ] 10.10.100.158       nb-hadoop-runtask08
[13 ] 10.10.100.160       nb-hadoop-runtask10
[14 ] 10.10.100.157       nb-hadoop-runtask07
[15 ] 10.10.100.156       nb-hadoop-runtask06
[16 ] 10.10.100.159       nb-hadoop-runtask09
[17 ] 10.10.100.5         nb-hadoop-runtask02
[18 ] 10.10.100.4         nb-hadoop-runtask01
[19 ] 10.10.100.195       4.client.adh
[20 ] 10.10.100.192       1.client.adh
[21 ] 10.10.100.197       6.client.adh
[22 ] 10.10.100.196       5.client.adh
[23 ] 10.10.100.194       3.client.adh
[24 ] 10.10.100.193       2.client.adh
'''
j2 = '''
[0  ] 10.10.132.56        mzqcloud-dts-1
[1  ] 172.81.251.110      txsh3-apigateway-1
[2  ] 212.64.43.116       txsh3-apigateway-2
[3  ] 212.64.69.34        txsh3-apigateway-3
[4  ] 172.81.211.59       txsh3-apigateway-4
[5  ] 172.81.206.151      Tsh3-dlistening-lableService1
[6  ] 172.81.245.240      Tsh3-dlistening-lableService2
[7  ] 192.168.8.139       3439.mzhen.cn
[8  ] 192.168.8.167       3449.mzhen.cn
[9  ] 192.168.8.166       3435.mzhen.cn
[10 ] 192.168.8.155       3438.mzhen.cn
[11 ] 192.168.8.120       3440.mzhen.cn
[12 ] 192.168.9.4         2097.mzhen.cn
[13 ] 192.168.9.111       2297.mzhen.cn
[14 ] 192.168.9.108       2294.mzhen.cn
[15 ] 10.10.0.127         Tbj3-apigateway-1
[16 ] 10.10.0.69          Tbj3-apigateway-2
[17 ] 10.10.132.48        Tbj3-apigateway-3
[18 ] 10.10.134.9         Tbj3-daas-jenkins
[19 ] 118.25.251.64       Tsh3-daas-testing01
'''
# 将上面的服务器信息整理为expect脚本需要的服务列表
final_servers = []

alias = {
    "t8": {'step_1': '1', 'step_2': '12', 'name': 'nb-hadoop-runtask08'},
    "t9": {'step_1': '1', 'step_2': '16', 'name': 'nb-hadoop-runtask09'},
    "c2": {'step_1': '1', 'step_2': '24', 'name': '2.client.adh'},
    "c5": {'step_1': '1', 'step_2': '22', 'name': '5.client.adh'},
    "2294": {'step_1': '2', 'step_2': '16', 'name': '2097.mzhen.cn'},
    "2294": {'step_1': '2', 'step_2': '18', 'name': '2294.mzhen.cn'},
    "2297": {'step_1': '2', 'step_2': '17', 'name': '2297.mzhen.cn'},
    "kg": {'step_1': '1', 'step_2': '13', 'name': 'nb-hadoop-runtask10'}
}

p = None

def get_terminal_size():
    s = struct.pack("HHHH", 0, 0, 0, 0)
    a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, s))
    return a[0], a[1]

def sigwinch_passthrough(sig, data):
    global p
    if not p.closed:
        p.setwinsize(*get_terminal_size())

def expect_ssh(server):
    try:
        global p
        print(server)
        # os.system("expect -f {}/expect_ssh.exp '{}' '{}'".format(sys.path[0], server["step_1"], server["step_2"]))
        
        p = pexpect.spawn("ssh %s@fort.mlamp.cn" % user)
        # Set the window size the same of current terminal window size
        p.setwinsize(*get_terminal_size())
        # Hook the window change signal so that the pexpect window size change as well
        signal.signal(signal.SIGWINCH, sigwinch_passthrough)
        p.expect('请选择目标资产：')
        p.sendline(server["step_1"])
        p.expect([re.compile("请输入命令或服务器ID.*"), re.compile(">>> .*")])
        p.sendline(server["step_2"])

        p.interact()
    except err:
        print(err)
        exit(1)

def cmp(a, b):
    return (a > b) - (a < b)

# 奇怪的排序
def csort(x, y):
    sx = x.split(".")
    sx.reverse()
    sy = y.split(".")
    sy.reverse()
    snum = max(len(sx), len(sy))
    for i in range(snum):
        if i + 1 > len(sx):
            return -1
        if i + 1 > len(sy):
            return 1
        l = max(len(sx[i]), len(sy[i]))
        t = cmp(sx[i].rjust(l, " "), sy[i].rjust(l, " "))
        if t is not 0:
            return t

def parse_servers():
    global final_servers
    j1_servers = j1.strip().split("\n")
    for s in j1_servers:
        ss = re.compile("\[|\s*").split(s)
        sss = {
            "name": ss[4],
            "step_1": "1",
            "step_2": ss[1]
        }
        final_servers.append(sss)

    j2_servers = j2.strip().split("\n")
    for s in j2_servers:
        ss = re.compile("\[|\s*").split(s)
        sss = {
            "name": ss[4],
            "step_1": "2",
            "step_2": ss[1]
        }
        final_servers.append(sss)
    
    final_servers = sorted(final_servers, key=functools.cmp_to_key(lambda x, y: csort(x['name'], y['name'])))

if __name__ == '__main__':
    server_num = -1
    server = None
    if len(sys.argv) > 1:
        arg1 = sys.argv[1]
        if alias.get(arg1):
            server = alias.get(arg1)
        else:
            parse_servers()
            server_num = sys.argv[1]
            server_num = int(server_num, 16)
            server = final_servers[server_num]
    else:
        parse_servers()
        print("{0:>4} |{1:>30}".format("Num", "Host"))
        print("-" * 36)
        for i, s in enumerate(final_servers):
            print("{0:>4x} |{1:>30}".format(i, s['name']))
        print("-" * 36)
        server_num = raw_input("输入要登录服务器序号: ")
        server_num = int(server_num, 16)
        server = final_servers[server_num]

    expect_ssh(server)
